package com.agileboot.domain.airport.danger;

import com.agileboot.common.core.page.PageDTO;
import com.agileboot.domain.airport.reform.db.SirReformMainEntity;
import com.agileboot.domain.airport.reform.db.SirReformMainService;
import com.agileboot.domain.airport.report.db.SirReportEntity;
import com.agileboot.domain.airport.report.db.SirReportService;
import com.agileboot.domain.common.command.BulkOperationCommand;

import com.agileboot.domain.airport.danger.db.DangerSourceEntity;
import com.agileboot.domain.airport.danger.db.DangerSourceService;
import com.agileboot.domain.airport.danger.command.AddDangerSourceCommand;
import com.agileboot.domain.airport.danger.command.UpdateDangerSourceCommand;
import com.agileboot.domain.airport.danger.dto.DangerSourceDTO;
import com.agileboot.domain.airport.danger.model.DangerSourceModel;
import com.agileboot.domain.airport.danger.model.DangerSourceModelFactory;
import com.agileboot.domain.airport.danger.query.DangerSourceQuery;
import com.agileboot.domain.system.dept.db.SysDeptEntity;
import com.agileboot.domain.system.dept.db.SysDeptService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 危险源应用服务
 * @author [your-name]
 */
@Service
@RequiredArgsConstructor
public class DangerSourceApplicationService {

    private final DangerSourceService dangerSourceService;

    private final DangerSourceModelFactory modelFactory;

    private final SysDeptService sysDeptService; // 新增依赖

    private final SirReformMainService sirReformMainService; // 新增依赖

    private final SirReportService sirReportService; // 新增依赖


    public PageDTO<DangerSourceDTO> getDangerSourceList(DangerSourceQuery query) {
        Page<DangerSourceEntity> page = dangerSourceService.page(query.toPage(), query.toQueryWrapper());
        List<DangerSourceDTO> records = convertToDTOs(page.getRecords());
        return new PageDTO<>(records, page.getTotal());
    }

    /**
     * 查询满足条件的所有危险源，不分页
     */
    public List<DangerSourceDTO> getDangerSourceListAll(DangerSourceQuery query) {
        List<DangerSourceEntity> all = dangerSourceService.list(query.toQueryWrapper());
        return convertToDTOs(all);
    }

    public DangerSourceDTO getDangerSourceInfo(Long dangerSourceId) {
        DangerSourceEntity entity = dangerSourceService.getById(dangerSourceId);
        return convertToDTOs(Collections.singletonList(entity)).get(0);
    }

    private List<DangerSourceDTO> convertToDTOs(List<DangerSourceEntity> entities) {
        if (entities.isEmpty()) {
            return Collections.emptyList();
        }

        // 收集所有部门ID
        Set<Long> deptIds = new HashSet<>();
        // 收集所有整改ID和问题ID
        Set<Long> reformIds = new HashSet<>();
        Set<Long> questionIds = new HashSet<>();

        for (DangerSourceEntity entity : entities) {
            if (entity.getDutyDeptId() != null) {
                deptIds.add(entity.getDutyDeptId());
            }
            if (entity.getActionDeptId() != null) {
                deptIds.add(entity.getActionDeptId());
            }
            if (entity.getRelatedReformId() != null) {
                reformIds.add(entity.getRelatedReformId());
            }
            if (entity.getRelatedQuestionId() != null) {
                questionIds.add(entity.getRelatedQuestionId());
            }
        }

        Map<Long, SysDeptEntity> deptMap = new HashMap<>();
        if (!deptIds.isEmpty()) {
            deptMap = sysDeptService.getByDeptIds(new ArrayList<>(deptIds)).stream()
                    .collect(Collectors.toMap(SysDeptEntity::getDeptId, e -> e));
        }

        // 查询整改信息
        Map<Long, SirReformMainEntity> reformMap = new HashMap<>();
        if (!reformIds.isEmpty()) {
            List<SirReformMainEntity> reforms = sirReformMainService.listByIds(new ArrayList<>(reformIds));
            reformMap = reforms.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toMap(SirReformMainEntity::getReformId, e -> e));
        }

        // 查询问题信息
        Map<Long, SirReportEntity> questionMap = new HashMap<>();
        if (!questionIds.isEmpty()) {
            List<SirReportEntity> questions = sirReportService.listByIds(new ArrayList<>(questionIds));
            questionMap = questions.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toMap(SirReportEntity::getReportId, e -> e));
        }

        // 转 DTO 并设置部门名称
        List<DangerSourceDTO> dtos = new ArrayList<>();
        for (DangerSourceEntity entity : entities) {
            DangerSourceDTO dto = new DangerSourceDTO(entity);

            if (entity.getDutyDeptId() != null) {
                SysDeptEntity dept = deptMap.get(entity.getDutyDeptId());
                if (dept != null) {
                    dto.setDutyDeptName(dept.getDeptName());
                }
            }

            if (entity.getActionDeptId() != null) {
                SysDeptEntity dept = deptMap.get(entity.getActionDeptId());
                if (dept != null) {
                    dto.setActionDeptName(dept.getDeptName());
                }
            }

            // 设置整改标题
            if (entity.getRelatedReformId() != null) {
                SirReformMainEntity reform = reformMap.get(entity.getRelatedReformId());
                if (reform != null) {
                    dto.setReformTittle(reform.getReformTitle());
                }
            }

            // 设置问题标题
            if (entity.getRelatedQuestionId() != null) {
                SirReportEntity question = questionMap.get(entity.getRelatedQuestionId());
                if (question != null) {
                    dto.setReportTittle(question.getTitle());
                }
            }

            dtos.add(dto);
        }

        return dtos;
    }

    public void addDangerSource(AddDangerSourceCommand command) {
        DangerSourceModel model = modelFactory.create();
        model.loadFromAddCommand(command);

        model.checkNameUnique();

        dangerSourceService.save(model);
    }

    public void updateDangerSource(UpdateDangerSourceCommand command) {
        DangerSourceModel model = modelFactory.loadById(command.getDangerSourceId());
        model.loadFromUpdateCommand(command);

        model.checkNameUnique();

        dangerSourceService.updateById(model);
    }

    public void deleteDangerSource(BulkOperationCommand<Long> deleteCommand) {
        dangerSourceService.removeBatchByIds(deleteCommand.getIds());
    }
}
